<script setup lang="ts">
import { InfoFilled } from "@element-plus/icons-vue";

interface Permission {
  id: number;
  name: string;
  description: string;
  created_at: string;
  updated_at: string;
  pid: number;
  children?: Permission[];
}

interface Props {
  permissions: Permission[];
  selectedPermissions: Set<number>;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: "change", id: number, checked: boolean): void;
}>();

const handleChange = (id: number, checked: boolean) => {
  emit("change", id, checked);
};
</script>

<template>
  <div class="permission-group">
    <div
      v-for="permission in permissions"
      :key="permission.id"
      class="permission-item"
    >
      <el-checkbox
        :model-value="selectedPermissions.has(permission.id)"
        @update:model-value="checked => handleChange(permission.id, checked)"
      >
        <span class="permission-name">{{ permission.name }}</span>
      </el-checkbox>
      <el-tooltip v-if="permission.description" effect="dark" placement="top">
        <template #content>{{ permission.description }}</template>
        <el-icon class="info-icon"><InfoFilled /></el-icon>
      </el-tooltip>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.permission-group {
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 4px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid transparent;
  border-radius: 4px;
  transition: all 0.2s;

  &:hover {
    border-color: var(--el-border-color-hover);
    box-shadow: 0 2px 4px rgb(0 0 0 / 5%);
  }

  &:last-child {
    margin-bottom: 0;
  }

  .permission-name {
    flex: 1;
    margin-right: 8px;
    font-size: 14px;
  }

  .info-icon {
    margin-left: 8px;
    font-size: 16px;
    color: var(--el-text-color-secondary);
    cursor: pointer;
    transition: color 0.2s;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

:deep(.el-checkbox) {
  display: flex;
  align-items: center;

  .el-checkbox__label {
    line-height: 1.4;
    word-break: break-all;
    white-space: normal;
  }

  &.is-checked {
    .permission-item {
      background-color: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary-light-7);
    }
  }
}
</style>
